#!/bin/bash

######################################################
# file : 
# Author : Anil Kainikara (anilkumar911@gmail.com)
# 
#
# This code is licenced under the GPL.
#
######################################################

PATTERN=
EXCLUDE_PATTERN=
#-v x_pattern=$EXCLUDE_PATTERN

findpattern()
{
  sqlite3 /home/anil/.local/share/diary.db "select * from entries order by year,month,day"  |
            awk -v pattern="$PATTERN" ' BEGIN {
                       IGNORECASE=1;
                       datefound=0;
                       date="";
                       content=0;
                       prevdate="";
                       pattern=tolower(pattern);
                       x_pattern=tolower(x_pattern);
                       }
              /^[0-9][0-9][0-9][0-9]\|[0-9]+\|[0-9].*/ {
                             datefound=1;
                             if(content != 0){ print prevdate "\n----------"};
                             content=0;
                             prevdate=$0 }
              tolower($0) ~ pattern { 
                             if( x_pattern != ""){
                               if( tolower($0) !~ x_pattern ){
                                 content=1;
                                 print $0;
                               }
                             }else{
                              content=1;
                              print $0;
                             } } 
               END {
                 if(content != 0){ print prevdate "\n----------"};
                 }'

}

function parseCommandLine
{
  while getopts e:x: name
  do
    case $name in
    e) PATTERN=$PATTERN"|$OPTARG" ;;
    x) EXCLUDE_PATTERN=$EXCLUDE_PATTERN"|$OPTARG" ;;
    ?) usage
       exit 1;;
    esac
  done
}

usage()
{
   echo $0 "[-e <pattern ]"
}
main()
{
  parseCommandLine $@
  PATTERN=`echo $PATTERN | sed -e"s/^|//"`
  EXCLUDE_PATTERN=`echo $EXCLUDE_PATTERN | sed -e"s/^|//"`
  if [[ -z $PATTERN ]]
  then
     usage $@
     exit 1;
   fi
  findpattern 
}

main $@
